{include file="public/header296" /}
<div class="layui-fluid">
  <div class="layui-card">
  <div class="layui-form" lay-filter="layuiadmin-app-form-list" id="layuiadmin-app-form-list" style="padding: 20px 30px 0 0;">
    <div class="layui-form-item">
      <label class="layui-form-label">标题</label>
      <div class="layui-input-block">
        <input type="text" lay-verify="required" name="name" value="{$item.name|default=''}" autocomplete="on" placeholder="标题长度不能超过100字符" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">分类</label>
      {notempty name="item['category_list']"}
      <div class="layui-input-inline">
        <select name="category_id"  lay-filter="category_id">
          <option value="">请选择分类</option>
          {volist name="item['category_list']" id="vo"}
            <option value="{$vo.id}" {notempty name="item.category_id"}{eq name="item.category_id" value="$vo.id"}selected{/eq}{/notempty}>{$vo.name}</option>
          {/volist}
        </select>
      </div>
      {else /}
      <div class="layui-input-inline">
        <button class="layui-btn layuiadmin-btn-list" data-type="category">创建分类</button>
      </div>
      {/notempty}
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">开发类型</label>
      <div class="layui-input-block">
        {volist name="item['dev_types']" id="type" key="index"}
        <input type="checkbox" class="dev_type" lay-filter="dev_type" value="{$index}" title="{$type}" {notempty name="item.dev_type"}{in name="$index" value="$item['dev_type']"}checked{/in}{/notempty} lay-skin="primary" />
        {/volist}
      </div>
    </div>
    <div class="layui-upload">
      <label class="layui-form-label">缩略图</label>
      <button type="button" class="layui-btn" id="test-upload-normal">上传图片</button>
      <div class="layui-upload-list">
        <label class="layui-form-label"></label>
        <img class="layui-upload-img" id="test-upload-normal-img" width="150" {notempty name="item.thumb_url"}src="{$item.thumb_url}"{/notempty} ">
      </div>
      <label class="layui-form-label"></label>
      <p id="test-upload-demoText"></p>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">关键字(seo)</label>
      <div class="layui-input-block">
        <input type="text" name="keywords" value="{$item.keywords|default=''}" placeholder="请输入关键字" autocomplete="on" class="layui-input">
        <p>多个用逗号隔开，但不要超过100个字符（包括中文，字符）</p>
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">摘要</label>
      <div class="layui-input-block">
        <textarea id="description" name="description" class="layui-textarea" lay-verify="summary">{$item.description|default=''}</textarea>
        <p>系统限制255字符以内</p>
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">标签</label>
      <div class="layui-input-block">
        {volist name="item['tag_list']" id="tag"}
          <input type="checkbox" class="tag_ids" lay-filter="tag_ids" value="{$tag.id}" title="{$tag.name}" {notempty name="item.tag_ids"}{in name="$tag.id" value="$item['tag_ids']"}checked{/in}{/notempty} lay-skin="primary" />
        {/volist}
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">上传多图</label>
      <div class="layui-upload-drag" id="multi-upload-img">
        <i class="layui-icon">&#xe654;</i>
        <p>选择图片</p>
      </div>
      <div id="multi-file-list" style="float: left;">
        {notempty name="item['images_urls']"}
        {volist name="item['images_urls']" id="vo" key="k"}
          <span id="{$k}">
            <img src="{$vo}" style='width:117.33px; height:129.33px; margin-right:5px;' />
            <a type='button' style='margin-right:5px;cursor: pointer;' onclick='delImg(this)'><i class='layui-icon'>&#xe640;</i></a>
          </span>
        {/volist}
        {/notempty}
      </div>
      <input type="hidden" name="images_url" id="images_url" value="{$item.images_url}" />
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">排序id</label>
      <div class="layui-input-inline">
        <input type="text" name="sort" value="{$item.sort}" autocomplete="on" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">是否推荐</label>
      <div class="layui-input-inline">
        {notempty name="item.is_rec"}
          <input type="checkbox" name="is_rec" lay-skin="switch" lay-text="是|否" {eq name="item['is_rec']" value="1"}checked{/eq} />
        {else /}
          <input type="checkbox" name="is_rec" lay-skin="switch" lay-text="是|否" />
        {/notempty}
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">是否发布</label>
      <div class="layui-input-inline">
        {notempty name="item.status"}
        <input type="checkbox" name="status" lay-skin="switch" lay-filter="switchStatus" lay-text="发布|隐藏" {eq name="item['status']" value="1"}checked{/eq} />
        {else /}
        <input type="checkbox" name="status" lay-skin="switch" lay-filter="switchStatus" lay-text="发布|隐藏" checked />
        {/notempty}
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">排序id</label>
      <div class="layui-input-inline">
        <input type="text" value="{$item.update_time}" class="layui-input" />
      </div>
    </div>
    <div class="layui-form-item layui-hide">
        <input type="hidden" name="id" value="{$item.id|default=0}" />
        <input type="hidden" name="thumb_url" id="thumb_url" value="{$item.thumb_url|default=''}" />
        <input type="hidden" name="tag_ids" id="tag_ids" value="{$item.tag_ids}" />
        <input type="hidden" name="dev_type" id="dev_type" value="{$item.dev_type|default=''}" />
      <input type="button" lay-submit lay-filter="Lay-app-form-edit" id="Lay-app-form-edit" value="编辑">
    </div>
  </div>
  </div>
</div>
<script>
  layui.use(['layer', 'form', 'upload'], function () {
        var $ = layui.$
            , form = layui.form
            , upload = layui.upload;

  // 普通图片上传
  var uploadInst = upload.render({
    elem: '#test-upload-normal'
    , url:"{:url('article/uploadThumb')}"
    , data: {path:'thumb'}
    , before: function(obj){
      obj.preview(function(index, file, result){
        $('#test-upload-normal-img').attr('src', result);
      });
    }
    , done: function(res){
      if(res.code > 0){
        return layer.msg(res.msg);
      }
      if(res.code == 0){
        $('#thumb_url').val(res.file_url);
        return layer.msg(res.msg);
      }
    }
    , error: function(){
      //演示失败状态，并实现重传
      var demoText = $('#test-upload-demoText');
      demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
      demoText.find('.demo-reload').on('click', function(){
        uploadInst.upload();
      });
    }
  });

    // 多图片上传
    var imgUrl = "{$item['images_url']}";
    var num = 0;
    var imgIndex = [];
    upload.render({
      elem: '#multi-upload-img'
      , url: "{:url('uploadFile/uploadPic')}"
      , auto:true
      , multiple: true
      , size: 0
      , accept: 'images'
      , acceptMime: 'images'
      , number: 10
      , choose: function(obj){
        num = imgUrl.split(";").length;
        if(num>10){
          return layer.msg("上传图片超过 10张", { icon : 2});
        }
        // 将每次选择的文件追加到文件队列
        var files = this.files = obj.pushFile();
        obj.preview(function(index, file, result){
          var imgSrc = "<span id='"+index+"'><img src = '"+result+"' style='width:117.33px;height:129.33px;margin-right:5px;'/>";
          imgSrc +="<a type='button' style='margin-right:5px;cursor: pointer;' onclick='delImg(this)'><i class='layui-icon'>&#xe640;</i></a></span>";
          $("#multi-file-list").append(imgSrc);
        });
      }
      , done: function(res, index){
        if(res.errno == 0) {
          // 删除数组文件中上传成功的图片，防止重复上传（重点）
          delete this.files[index];
          var url = '';
          url = res.data.url+';'
          imgUrl += url;
          imgIndex.push({
            index:index,
            url:url
          })
          //$('#images_url').val('');
          $('#images_url').val(imgUrl);
          return layer.msg(res.message);
        } else {
          return layer.msg('上传失败请重新选择上传');
        }
      }
    });

    // 删除上传图片
    window.delImg = function (obj){
      layer.confirm(
              '请确认是否删该图片!',
              {
                skin : 'layui-layer-admin',
                shade : .1
              },
              function(i){
                layer.close(i);
                var id = obj.parentNode.id;
                for(k in imgIndex){
                  var index, url;
                  index = imgIndex[k].index;
                  url = imgIndex[k].url;
                  if(id == index){
                    imgUrl = imgUrl.replace(url, '');
                    deleteImage(url, obj, imgUrl);
                    break;
                  }
                }
              });
    }

    /* 后台删除图片 */
    function deleteImage(url, obj, imgUrl){
      $.ajax({
        type : "POST",
        url : "{:url('UploadFile/DeletePicture')}",
        data : {
          'path': url
        },
        dataType : "json",
        async:false,
        success : function(res) {
          if (res.code == 0) {
            obj.parentNode.remove();
            $('#images_url').val(imgUrl);
            layer.msg('删除成功');
          }else{
            layer.msg('删除失败');
          }
        },
        error : function() {
          layer.msg('删除失败');
        }
      });
    }

  // 监听开关事件
  form.on('switch(switchStatus)', function(data){
    var contexts;
    var x = data.elem.checked;
    if (x==true) {
      contexts = "确定要发布么";
    } else {
      contexts = "确定要隐藏么";
    }
    layer.open({
      content: contexts
      , btn: ['确定', '取消']
      , yes: function (index, layero) {
        data.elem.checked = x;
        form.render();
        layer.close(index);
      }
      , btn2: function (index, layero) {
        data.elem.checked = !x;
        form.render();
        layer.close(index);
      }
      , cancel: function () {
        data.elem.checked = !x;
        form.render();
      }
    });
    return false;
  });

    // 获取 checkbox 选中值
    form.on('checkbox(tag_ids)', function(obj){
      var tagIds = $('input:checkbox[class="tag_ids"]:checked').map(function () {
        return $(this).val();
      }).get().join(",");
      $("#tag_ids").val(tagIds);
    });
    form.on('checkbox(dev_type)', function(obj){
      var industryIds = $('input:checkbox[class="dev_type"]:checked').map(function () {
        return $(this).val();
      }).get().join(",");
      $("#dev_type").val(industryIds);
    });

  /* 自定义验证规则 */
  form.verify({
    name: function(value){
      if(value.length < 5){
        return '标题至少得5个字符啊';
      }
    }
  });

  var $ = layui.$, active = {
    category: function(){
      window.location.href = "{:url('article/category')}";
    }
  }

  $('.layui-btn.layuiadmin-btn-list').on('click', function(){
    var type = $(this).data('type');
    active[type] ? active[type].call(this) : '';
  });


  const { createEditor, createToolbar} = window.wangEditor

  const editorConfig = {
    placeholder: 'Type here',
    onChange(editor) {
      const html = editor.getHtml()
      console.log('editor content', html)

      // 获取内容
      $("#editor-content").val(editor.getHtml())
      // 选中文字字数
      const selectionText = editor.getSelectionText()
      document.getElementById('selected-length').innerHTML = selectionText.length
      // 全部文字字数
      const text = editor.getText().replace(/\n|\r/mg, '')
      document.getElementById('total-length').innerHTML = text.length
    },
    // 上传图片配置
    MENU_CONF: {}
  }
  editorConfig.MENU_CONF['uploadImage'] = {
    server: '{:url("uploadFile/uploadPic")}',
    timeout: 5 * 1000,
    fieldName: 'file',
    meta: { token: 'xxx', path: 'picture' },
    metaWithUrl: true,
    headers: { Accept: 'text/x-json' },
    maxFileSize: 5 * 1024 * 1024,
    limit: 1,

    onSuccess(file, res) {
      console.log('onSuccess---', file, res)
    },
    onFailed(file, res) {
      console.log('onFailed---', file, res)
    },
    onError(file, err, res) {
      console.error('onError---', file, err, res)
    },
  }

  const editor = createEditor({
    selector: '#editor-container',
    html: '{$item.content|raw|default=""}',
    config: editorConfig,
    mode: 'default'
  })

  const toolbarConfig = {}
  const toolbar = createToolbar({
    editor,
    selector: '#toolbar-container',
    config: toolbarConfig,
    mode: 'default'
  })
})
</script>
{include file="public/footer" /}